<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/25
 * Time: 15:41
 */

namespace app\api\model;

use think\Exception;
use think\Model;

class HotelRoomSku extends Model
{
    //创建RoomSku
    public function createRoomSkus($data)
    {
        $this->startTrans();
        try{
            //1 关联酒店的规格
            if(empty($data['hotel_id'])) return '缺少HotelID';
            if(empty($data['spec_id'])) return '缺少SpecID';
            db('hotel_spu_spec_value')->where('hotel_id',$data['hotel_id'])->delete();
            db('hotel_room_sku_price')->where('hotel_id',$data['hotel_id'])->delete();
            db('hotel_spu_spec_value')->insert([
                'hotel_id'=>$data['hotel_id'],
                'spec_id'=>$data['spec_id'],
                'attr_json'=>$data['attr_json'],
                'create_time'=>time(),
            ]);
            //2 创建房间SKU 和 关联属性
            //2.1 删除所有的酒店房间信息
            db('hotel_room_sku')->where('hotel_id',$data['hotel_id'])->delete();
            //2.2 添加所有酒店房间信息
            foreach ($data['room_skus'] as $key=>$value){
                $attr_value_names = db('hotel_spu_attr_value')->where(['id'=>['in',$value['attr_ids']]])->column('attr_value');
                $this->insert([
                    'hotel_id'=>$data['hotel_id'],
                    'name'=>implode(' , ',$attr_value_names),
                    'room_code'=>$value['room_code'],
                    'stock'=>$value['stock'],
                    'market_price'=>$value['market_price'],
                    'sales_price'=>$value['sales_price'],
                    'cost_price'=>$value['cost_price'],
                    'create_time'=>time(),
                ]);
                $insertId = db()->getLastInsID();
                $roomSkuAttrs = [];
                foreach ($value['attr_ids'] as $attr_value_id){
                    $roomSkuAttrs[] = [
                        'room_id'=>$insertId,
                        'attr_value_id'=>$attr_value_id,
                        'create_time'=>time()
                    ];

                }
                if(!empty($roomSkuAttrs)){
                    db('hotel_room_attr_value')->insertAll($roomSkuAttrs);
                }
            }
            $this->commit();
        }catch(Exception $e){
            $this->rollback();
            return $e->getMessage();
        }
    }

    public function getRoomSkusByHotelId($hotel_id)
    {
        if(empty($hotel_id)) return [];
        return $this->where('hotel_id',$hotel_id)->select();
    }
}